package org.raymond.iworks.study.netty.atguigu.netty.codec2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import lombok.extern.slf4j.Slf4j;
import org.raymond.iworks.study.netty.atguigu.netty.codec2.model.MyMessage;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class ProtoServer {
    public static void main(String[] args) throws Exception {
        int port = 6666;
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(2);
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workGroup)
                    .option(ChannelOption.SO_BACKLOG, 128) // tcp/ip协议,listen函数中的backlog参数,用来初始化服务端可连接队列
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持连接
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // 指定对那种对象进行解码
                                    .addLast(new ProtobufDecoder(MyMessage.getDefaultInstance()))
                                    .addLast(new ProtoServerHandler());
                        }
                    });
            // 绑定并启动
            ChannelFuture future = sb.bind(port).sync();
            future.addListener(f -> {
                if(f.isSuccess()){
                    log.info("监听端口 {} 成功", port);
                }else{
                    log.info("监听端口 {} 失败", port);
                }
            });
            // 对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
